package org.winthedocs.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class Utils {
    public static List<String> getContentByParagraph(Path filePath) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(filePath.toFile()));
        List<String> contentList = new ArrayList<>();

        String line;
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = br.readLine()) != null) {
            if ("".equals(line)) {
                contentList.add(stringBuilder.toString());
                stringBuilder.delete(0, stringBuilder.length());
            }
            stringBuilder.append(line);
            stringBuilder.append(System.lineSeparator());

        }
        return contentList;
    }

    /**
     * 获取指定路径中所有md和rst文件
     *
     * @param path
     * @return
     */
    public static List<String> getFiles(String path) throws IOException {
        List<String> files = new ArrayList<String>();
        File f = new File(path);
        if (f.isDirectory()) {
            File[] files1 = f.listFiles();
            for (int i = 0; i < files1.length; i++) {
                files.addAll(getFiles(files1[i].getPath()));
            }
        } else if (f.isFile()) {
            String suffix = f.getPath().substring(f.getPath().lastIndexOf(".") + 1);
            if ("rst".equals(suffix) || "md".equals(suffix)) {
                files.add(f.getPath());
            }
        }
        return files;
    }

    /**
     * 获取相对目录
     *
     * @param list
     * @param rootPath
     * @return
     */
    public static List<String> getRelativePath(List<String> list, String rootPath) {
        List<String> result = new ArrayList<String>();

        for (String s : list) {
            int i = s.lastIndexOf(rootPath);
            String substring = s.substring(rootPath.length() + 1);
            result.add(substring);
        }
        return result;
    }

    /**
     * 拼接完整文件路径
     *
     * @param rootPath
     * @param relativePath
     * @return
     */
    public static Path getFullPath(String rootPath, String relativePath) {
        if (!rootPath.endsWith(File.separator) && !relativePath.startsWith(File.separator)) {
            return Paths.get(rootPath + File.separator + relativePath);
        }
        return Paths.get(rootPath + relativePath);

    }
}
